package com.iqik.base.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * netty优点：
 *      对各种传输协议提供统一的API
 *      高度可定制的线程模型，支持单线程、一个或多个线程池
 *      更高的吞吐量，低的延迟
 *      更少的资源消耗
 *      最小化不必要的内存拷贝
 *         <dependency>
 *             <groupId>io.netty</groupId>
 *             <artifactId>netty-all</artifactId>
 *             <version>4.1.6.Final</version>
 *         </dependency>
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 1. 创建2个线程池对象
        // bossGroup 负责接收用户连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // workGroup 负责处理用户io操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // 2. 创建启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 3. 设置启动引导类
        // 添加到组中，两个线程池，parentGroup(bossGroup)用于接收用户连接，childGroup（workGroup）负责读写
        serverBootstrap.group(bossGroup, workGroup)
                // 设置通道类型
                .channel(NioServerSocketChannel.class)
                // 绑定一个初始化监听
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    // 事件监听通道
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取pipeline
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 绑定编码
                        pipeline.addFirst(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        // 绑定业务逻辑
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {

                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
                                //获取入栈信息,打印客户端传递的数据
                                System.out.println(msg);
                            }
                        });
                    }
                });

        // 4. 启动引导类绑定端口
        ChannelFuture channelFuture = serverBootstrap.bind(8201).sync();
        // 5. 关闭通道
        channelFuture.channel().closeFuture().sync();
    }

}
